package com.example.administrator.mvptest.view.biz;


import android.os.Handler;

import com.example.administrator.mvptest.view.api.ApiManager;
import com.example.administrator.mvptest.view.api.HttpServiceManager;
import com.example.administrator.mvptest.view.databeans.ZhihuDaily;
import com.example.administrator.mvptest.view.databeans.ZhihuStory;
import com.example.administrator.mvptest.view.utils.OnEventLister;
import com.google.gson.Gson;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by Administrator on 2016-11-24.
 */
public class ZhihuDailyBiz {

    public void getStoryData(final String url,final OnEventLister<ArrayList<ZhihuStory>>eventLister)
    {
        final Handler handler=new Handler();
        new Thread(){
            public void  run(){
                try {
                    String result= HttpServiceManager.httpGet(url);
                    Gson gson=new Gson();
                    ZhihuDaily daily=gson.fromJson(result,ZhihuDaily.class);

                    final ArrayList<ZhihuStory>stories=daily.getStories();
                    if(stories!=null)
                    {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                eventLister.onSuccess(stories);
                            }
                        });
                    }
                    else {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                eventLister.onFial("-100", "获取日报失败！");
                            }
                        });
                    }
                }
                catch (Exception e)
                {
                     e.printStackTrace();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            eventLister.onFial("-100", "获取日报失败！");
                        }
                    });

                }
            }
        }.start();
    }

    public  void getStoryDataByRetrofit(final OnEventLister<ArrayList<ZhihuStory>> eventLister)
    {
        ApiManager apiManager=ApiManager.getInstance();
        Call<ZhihuDaily> Call=apiManager.getDataService().getZhihuDailyRetorfitOnly();
        //发送异步请求
        Call.enqueue(new Callback<ZhihuDaily>() {
            @Override
            public void onResponse(Call<ZhihuDaily> call, Response<ZhihuDaily> response) {
                eventLister.onSuccess(response.body().getStories());
            }

            @Override
            public void onFailure(Call<ZhihuDaily> call, Throwable t) {
                eventLister.onFial(t.getMessage(),"");
            }
        });
    }
}
